<template>
  <div class="app-main-container">
    <div class="app-main-title">
      {{ activityId ?'编辑活动':'新增活动' }}
      <div class="goback" @click="goBack">
        <i class="el-icon-refresh-left" /> 返回上一页
      </div>
    </div>

    <el-form
      ref="ruleForm"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="150px"
      label-suffix="："
    >
      <div class="property-title">活动信息</div>
      <el-form-item label="活动海报" prop="showPoster">
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            use-type="ACTIVITY_IMG"
            :fixed-number="[690, 388]"
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
        <el-upload
          class="device-uploader"
          accept=".jpg,.png"
          :auto-upload="false"
          :action="uploadFileUrl"
          :data="uploadData"
          :show-file-list="false"
          :on-change="addFileChange"
        >
          <i class="el-icon-plus uploader-icon" />
          <div
            v-show="param.showPoster"
            class="file"
            :style="'background-image: url(' + param.showPoster + ')'"
          >
            <div class="delete">
              <i
                class="el-icon-delete icon"
                @click.stop="deleteDeviceConfigAddImage"
              />
            </div>
          </div>
        </el-upload>
        <div style="display: inline-block">
          {{ "建议图片尺寸690px X 388px" }}
        </div>
      </el-form-item>
      <el-form-item label="活动名称" prop="name">
        <el-input
          v-model="param.name"
          class="w400"
          type="text"
          placeholder="请输入活动名称"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="活动价格" prop="price">
        <el-input
          v-model="param.price"
          class="w400"
          type="number"
          :disabled="Boolean(activityId) && activityStatus === '1' || Boolean(activityId) && activityStatus === '2'"
          placeholder="请输入活动价格"
        />
      </el-form-item>
      <div style="display: flex; align-items: center">
        <el-form-item label="活动时间" prop="startTime">
          <el-date-picker
            v-model="param.startTime"
            type="datetime"
            placeholder="选择开始日期时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <div class="division-line" style="margin-bottom: 22px">~</div>
        <el-form-item label-width="0" prop="endTime">
          <el-date-picker
            v-model="param.endTime"
            type="datetime"
            placeholder="选择结束日期时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
          />
        </el-form-item>
      </div>
      <el-form-item label="活动地点" prop="siteName">
        <el-input
          v-model="param.siteName"
          class="w400"
          type="text"
          placeholder="请输入场区场地"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="报名截止时间" prop="applyEndTime">
        <el-date-picker
          v-model="param.applyEndTime"
          :picker-options="pickerOptions"
          type="datetime"
          :disabled="Boolean(activityId) && activityStatus === '2'"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item label="活动奖励积分" prop="shareIntegral">
        <el-input
          v-model="param.shareIntegral"
          class="w400"
          onkeyup="value=value.replace(/[^\d^\.]/g,'')"
          oninput="if(value<0) { value = ''}"
          type="number"
          placeholder="请输入活动奖励积分"
        />
        <div class="placeholder9">活动报名获得积分</div>
      </el-form-item>
      <el-form-item label="排序码" prop="sortNum">
        <el-input
          v-model="param.sortNum"
          class="w400"
          type="text"
          placeholder="请输入排序码"
          maxlength="10"
          oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
        />
      </el-form-item>
      <div class="line-style" />

      <div class="property-title">详情信息</div>
      <el-form-item label="活动主题" prop="theme">
        <el-input
          v-model="param.theme"
          class="w400"
          type="text"
          placeholder="请输入活动主题"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item label="主办方" prop="sponsor">
        <el-input
          v-model="param.sponsor"
          class="w400"
          type="text"
          placeholder="请输入主办方"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item label="承办方" prop="organizer">
        <el-input
          v-model="param.organizer"
          class="w400"
          type="text"
          placeholder="请输入承办方"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item label="活动详情" prop="info">
        <div class="secondColor">注：图片不支持复制粘贴，仅支持本地上传；</div>
        <quill-editor
          ref="myTextEditor"
          v-model="param.info"
          placeholder="请输入活动详情"
          class="myQuillEditor"
          :options="quillOption"
        />
      </el-form-item>
      <div class="line-style" />

      <div class="property-title">会员折扣</div>
      <el-form-item label="折扣类型" prop="discountType">
        <el-select v-model="param.discountType" placeholder="请选择折扣类型">
          <el-option
            v-for="item in zkList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <div
        v-if="param.discountType == '1'"
        style="display: flex; flex-wrap: wrap"
      >
        <el-form-item
          v-for="vip in vipTypeList"
          :key="vip.id"
          align="center"
          :label="vip.cardName"
          style="width: 50%"
          :prop="`discountMap.${vip.id}`"
          :rules="{
            required: true,
            message: '请输入会员折扣',
            trigger: 'blur',
          }"
        >
          <el-input
            v-model="param.discountMap[vip.id]"
            onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            oninput="if(value<0||value>1) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
            type="text"
            placeholder="请输入会员折扣(保留两位小数)"
            maxlength="20"
          />
        </el-form-item>
      </div>
      <el-form-item>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="onSubmit()"
        >提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import quillConfig from '@/api/sc.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import Cropper from '@/components/cropper'
import {
  uploadFile,
  cardList,
  // getProjectList,
  // getAreaList,
  spaceList,
  startActivity,
  activityQueryForEdit,
  activitySaveForEdit
} from '@/api'
export default {
  name: 'ActivityManagementAdd',
  components: {
    quillEditor,
    Cropper
  },
  data() {
    return {
      activityId: '',
      activityStatus: '',
      quillOption: quillConfig,
      uploadFileUrl: uploadFile,
      dialogCropperVisible: false,
      subLoading: false,
      vipTypeList: [],
      param: {
        discountMap: {}
      },
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
          )
        }
      },
      uploadData: {
        folder: 'ACTIVITY_IMG',
        type: ''
      },
      lxList: [
        { value: '01', label: '团体课' },
        { value: '02', label: '私教课 ' }
      ],
      lmList: [
        { value: '01', label: '足球' },
        { value: '02', label: '篮球' },
        { value: '03', label: '羽毛球' }
      ],
      payStatusList: [
        { value: '0', label: '未支付' },
        { value: '1', label: '过期未付' },
        { value: '2', label: '已取消' },
        { value: '3', label: '已支付' }
      ],
      zkList: [
        { value: '0', label: '默认折扣' },
        { value: '1', label: '自定义折扣' }
      ],
      jlList: [],
      venueId: sessionStorage.getItem('venueId'),
      rules: {
        showPoster: [
          { required: true, message: '请上传活动海报', trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        price: [
          {
            pattern: /^(([0-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            required: true,
            message: '请输入正确活动价格(元),最多保留2位小数',
            trigger: 'change'
          }
        ],
        startTime: [
          { required: true, message: '请选择活动开始日期', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择活动结束日期', trigger: 'change' }
        ],
        siteName: [
          { required: true, message: '请输入场区场地', trigger: 'blur' }
        ],
        applyEndTime: [
          { required: true, message: '请选择报名截止时间', trigger: 'blur' }
        ],
        shareIntegral: [
          { required: true, message: '请输入活动奖励积', trigger: 'blur' }
        ],
        theme: [{ required: true, message: '请输入活动主题', trigger: 'blur' }],
        sponsor: [{ required: true, message: '请输入主办方', trigger: 'blur' }],
        organizer: [
          { required: true, message: '请输入承办方', trigger: 'blur' }
        ],
        info: [{ required: true, message: '请输入活动详情', trigger: 'blur' }],
        discountType: [
          { required: true, message: '请选择折扣类型', trigger: 'change' }
        ],
        optionImg: '',
        files: {},
        fileinfo: {}
      }
    }
  },
  created() {
    this.getCardList()
    // if (this.$route.query.id) {
    //   // this.$route.title = '编辑活动'
    //   this.getActivityDetailInfo(this.$route.query.id)
    // } else {
    //   // this.$route.title = '新增活动'
    // }
    if (this.$route.query.id) {
      this.getActivityDetailInfo(this.$route.query.id)
      this.activityId = this.$route.query.id
      if (this.$route.query.type && this.$route.query.type === 'copy') {
        this.activityId = ''
      } else {
        this.activityStatus = this.$route.query.status
      }
    } else {
      this.activityId = ''
    }
  },
  activated() {
    // if (this.$route.query.id) {
    //   this.getActivityDetailInfo(this.$route.query.id)
    // } else {
    //   this.param = {
    //     discountMap: {}
    //   }
    //   this.fileinfo = {}
    //   setTimeout(() => {
    //     this.$refs.ruleForm.clearValidate()
    //   }, 2000)
    // }
  },
  methods: {
    check_num(e) {
      this.param.rs[e] = this.param.rs[e].replace(/[^\d]/g, '')
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'showPoster', config.showUrl)
        this.$set(this.param, 'poster', config.insertUrl)
        this.fileinfo = config
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || '上传失败')
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    getCardList() {
      // 获取卡类型列表
      cardList({
        param: {
          type: '1'
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.vipTypeList = res.recordList
        })
        .catch((err) => {
          console.log(err)
        })
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 删除已上传图片
    deleteDeviceConfigAddImage() {
      this.$set(this.param, 'poster', '')
      this.$set(this.param, 'showPoster', '')
    },
    getActivityDetailInfo(activityId) {
      Promise.all(
        // 获取卡类型列表
        [
          cardList({}),
          activityQueryForEdit({
            param: {
              activityId
            }
          })
        ]
      )
        .then((res) => {
          this.vipTypeList = res[0].recordList
          this.param = res[1].record
          const discountmap = res[1].record.discountMap
          if (res[1].record.discountType === '0') {
            this.$set(this.param, 'discountMap', {})
          } else {
            this.$set(this.param, 'discountMap', discountmap)
          }
        })
        .catch(() => {})
    },
    getSpaceList(id) {
      this.$set(this.param, 'dd', [id, ''])
      spaceList({ param: { id }}).then((res) => {
        this.cdList = res.recordList
      })
    },
    onSubmit() {
      var currentDate = new Date().getTime()
      var startTime = new Date(this.param.startTime).getTime()
      var endTime = new Date(this.param.endTime).getTime()
      var applyEndTime = new Date(this.param.applyEndTime).getTime()
      if (endTime < startTime) {
        this.$message.warning('活动结束时间不能早于活动开始时间')
        return
      }
      if (endTime <= currentDate) {
        this.$message.warning('活动结束时间不能早于当前时间')
        return
      }
      if (applyEndTime > startTime) {
        this.$message.warning('报名截止时间不能晚于活动开始时间')
        return
      }
      const param = { ...this.param }
      param.venueId = sessionStorage.getItem('venueId')
      if (this.activityId) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.subLoading = true
            activitySaveForEdit({ param: param })
              .then((res) => {
                // console.log(res)
                this.subLoading = false
                if (res.errorCode === '000000') {
                  this.$message.success('编辑成功')
                  this.$router.replace(`/activityManagement/activityManagementList?renovate=1`)
                }
              })
              .catch((er) => {
                this.subLoading = false
                console.log(er)
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.subLoading = true
            startActivity({
              param: param
            })
              .then((res) => {
                this.subLoading = false
                if (res.errorCode === '000000') {
                  this.$message.success('新增成功')
                  this.$router.replace(`/activityManagement/activityManagementList?renovate=1`)
                }
              })
              .catch((err) => {
                this.subLoading = false
                console.log(err)
              })
          } else {
            return false
          }
        })
      }
    },
    // 返回上一页
    goBack() {
      // this.$router.go(-1)
      this.$router.replace(`/activityManagement/activityManagementList`)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.line-style {
  margin-bottom: 20px;
}
.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}

.division-line {
  text-align: center;
  display: inline-block;
  color: #999;
  width: 50px;
}
</style>
